<?php

namespace App\Api\Controllers;

use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;
use App\Api\Requests\VerificationCodeRequest;

class VerificationCodesController extends Controller
{
    public function store(VerificationCodeRequest $request, EasySms $easySms)
    {
        $mobile = $request->mobile;

        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        //$code = 1234;

        try {
            $result = $easySms->send($mobile, [
                'template'  =>  '196733',
                'data' => [
                    'code' => $code,
                ],
            ]);
        } catch (\GuzzleHttp\Exception\ClientException $exception) {
            $response = $exception->getResponse();
            $result = json_decode($response->getBody()->getContents(), true);
            return $this->error($result['msg'] ?? '短信发送异常');
        }

        $key = 'verificationCode_'.str_random(15);
        $expiredAt = now()->addMinutes(10);
        // 缓存验证码 10分钟过期。
        \Cache::put($key, ['mobile' => $mobile, 'code' => $code], $expiredAt);

        return $this->success([
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ]);
    }
}
